<template>
  <a-input-group compact>
    <a-select v-model:value="dateType" style="width: 25%" @change="handleSelectChange">
      <a-select-option :value="0">年</a-select-option>
      <a-select-option :value="1">月</a-select-option>
      <a-select-option :value="2">日</a-select-option>
    </a-select>
    <a-range-picker
      v-model:value="dateValue"
      @panelChange="handlePanelChange"
      @change="handlePickerChange"
      :format="pickerFormat[dateType]"
      :valueFormat="pickerValueFormat[dateType]"
      :mode="pickerMode[dateType]"
      style="width: 70%"
    />
  </a-input-group>
</template>
<script lang="ts">
  import moment, { Moment } from 'moment';
  import { computed, defineComponent, reactive, ref, toRaw } from 'vue';
  import { Select, Input, DatePicker } from 'ant-design-vue';
  moment.suppressDeprecationWarnings = true;

  // 获取本年第一天
  const date = new Date();
  date.setMonth(0);
  date.setDate(1);
  date.setHours(0);
  date.setSeconds(0);
  date.setMinutes(0);

  const defultTimeValue = [moment(date), moment(new Date())];

  export default defineComponent({
    name: 'DateTypePicker',
    components: {
      Select,
      [Select.name]: Select,
      ASelectOption: Select.Option,
      [Input.name]: Input,
      [Input.Group.name]: Input.Group,
      [DatePicker.RangePicker.name]: DatePicker.RangePicker,
    },
    setup(_, { emit }) {
      const dateValue = ref<Moment[]>(defultTimeValue);

      const dateType = ref<number>(2);
      const pickerMode = reactive({
        0: ['year', 'year'],
        1: ['month', 'month'],
        2: ['date', 'date'],
      });

      const pickerFormat = reactive({
        0: 'YYYY',
        1: 'YYYY-MM',
        2: 'YYYY-MM-DD',
      });

      const pickerValueFormat = reactive({
        0: 'YYYY',
        1: 'YYYY-MM',
        2: 'YYYY-MM-DD',
      });

      const dateTimeStr = computed(() => {
        return dateValue.value.map((item) =>
          moment(item).format(pickerValueFormat[dateType.value])
        );
      });

      emit('change', {
        type: toRaw(dateType.value),
        value: toRaw(dateTimeStr.value),
      });
      function handleSelectChange() {
        emit('change', {
          type: toRaw(dateType.value),
          value: toRaw(dateTimeStr.value),
        });
      }
      function handlePanelChange(val: Moment[], _: string[]) {
        dateValue.value = val;
        emit('change', {
          type: toRaw(dateType.value),
          value: toRaw(dateTimeStr.value),
        });
      }
      function handlePickerChange() {
        emit('change', {
          type: toRaw(dateType.value),
          value: toRaw(dateTimeStr.value),
        });
      }
      return {
        dateValue,
        dateType,
        pickerFormat,
        handleSelectChange,
        pickerValueFormat,
        pickerMode,
        handlePanelChange,
        handlePickerChange,
      };
    },
  });
</script>
<style lang="less" scoped></style>
